
#include "ui_mainwindow.h"
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
     ui->setupUi(this);
     ui->menuSomething->hide();

     // list the possible statistics in combo box
     QStringList stats;
     stats << "Masters" << "Collisions" << "Received"<< "Avg Speed"<<"Avg Packet Size"<<"Avg Wait Time";
     ui->XcomboBox->insertItems(0, stats);
     ui->YcomboBox->insertItems(0, stats);

     simData = new SimData();
     simDataArray[0] = simData;
     simData->masters =0;
     simData->maxpacket =0;
     simData->minpacket =0;
     simData->speed =0;

     paramsWindow = new GetParams(this);

     drawSim = new DrawSim(this);

     plotWindow = new Plot(this);

     myEnet = new Enet(this);

     simCount = 0; // increment when you start a new sim


     drawSim->setAutoFillBackground(true);
     QRect r(QPoint(60,320),QSize(621,321));
     drawSim->setGeometry(r);

     QObject::connect( this, SIGNAL( showSignal() ), &*paramsWindow, SLOT( shown() ) );

     QObject::connect( &*paramsWindow, SIGNAL( paramsSaved(int,int,int,int) ), this, SLOT( saveParams(int,int,int,int) ) );
     QObject::connect( &*paramsWindow, SIGNAL( paramsNotSaved() ), this, SLOT(dontSaveParams() ) );

     QObject::connect( this, SIGNAL( mastersChanged(int) ), &*drawSim, SLOT( changeMasters(int) ) );
     QObject::connect( this, SIGNAL( zoomChanged(int) ), &*drawSim, SLOT( changeZoom(int) ) );
     QObject::connect( this, SIGNAL( drawMasterAction(int, int) ), &*drawSim, SLOT( masterAction(int, int) ) );
     QObject::connect( this, SIGNAL( drawEnetStatus(int ) ), &*drawSim, SLOT( ethernetStatus(int ) ) );

     // initialize start/stop flag
     keepGoing = 0;

     // used for a delay when running a single sim
     // change to SStimer?
     timer = new QTimer(this);

     //connect timer to SingleSimCode
     connect(timer, SIGNAL(timeout()), this, SLOT(SingleSimCode()));

 }


void MainWindow::masterAction(int masterIndex, int action )
{
    emit drawMasterAction(masterIndex, action);
    if(action == 3)
    {
        trace(tr("Master %1 is checking.").arg(masterIndex));
    }
    else if( action == 2)
    {
        trace(tr("Master %1 is sending a packet.").arg(masterIndex));
    }
    else if(action == 1)
    {
        simData->received++;
        trace(tr("Master %1 received a packet.").arg(masterIndex));
    }
}

// receives a signal from the ethernet about its status
void MainWindow::ethernetStatus(int status)
{
   emit drawEnetStatus(status);
   if( status == 1) //colision
   {
       simData->colisions++;
       trace(tr("Collision %1.").arg(simData->colisions));
   }
}

void MainWindow::on_zoomSlider_valueChanged()
{
    int zoom;
    zoom = ui->zoomSlider->value();

    emit zoomChanged(zoom);
}

void MainWindow::saveParams(int masters, int max, int min, int speed)
{
    simData->masters = masters;
    simData->maxpacket = max;
    simData->minpacket = min;
    simData->speed = speed;
    paramsWindow->hide();

    for(int i = 0; i < masters; i++)
    {
        myMaster = new Master(this);
        masterArray[i] = myMaster;
    }

    emit mastersChanged(masters);

}

void MainWindow::dontSaveParams()
{
    paramsWindow->hide();

}


// shows a window that will save user simulation data
void MainWindow::on_paramsButton_clicked()
{
    // checks and sets the multiSim flag
    if(ui->singleSimButton->isChecked()){
        paramsWindow->multiSimTrue = false;
    }
    else{
        paramsWindow->multiSimTrue = true;
    }

    paramsWindow->show();

    for(int i = 0; i < simData->masters; i++)
    {
        delete masterArray[i];
        masterArray[i] = NULL;
    }

    emit showSignal();
}

void MainWindow::on_ShowGraphButton_clicked()
{
    plotWindow->show();
}

//destructor
MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::trace(QString str)
{
    ui->SimOutText->appendPlainText(str);
}

void MainWindow::on_StartButton_clicked()
{
    if(keepGoing == 0)
    { keepGoing = 1;
      emit startTheSim(simData->masters, simData->maxpacket, simData->minpacket, simData->speed);
    }else{
      keepGoing = 0;
      emit stopTheSim();
    }


    if(ui->singleSimButton->isChecked())
    {
    }
    else if(ui->multiSimButton->isChecked())
    {

    }



}



void MainWindow::SingleSimCode()
{
    if(keepGoing == 0)
    {
       timer->stop();
    }
    if(SingleSimStep%3 == 0)
    {


    }
    else
    {



    }
    SingleSimStep++;
}


void MainWindow::StartSim()
{
    int i =0;

    simData->colisions=0;
    simData->received=0;

   SingleSimStep = 0;

   if(ui->singleSimButton->isChecked())
   {
      //Single Sim code here

         //used for a delay
          //timeout signals SingleSimCode

            timer->start(100);

  }

  else if(ui->multiSimButton->isChecked())
  {
      //Multi Sim code here
      // no  delay
      while(keepGoing)
      {

       if(i%3 == 0)
       {

       }
       else
       {

       }
       i++;

       // this line is ESSENTIAL to let the program breathe
       qApp->processEvents ();

     }
  }



}


void MainWindow::on_actionNew_triggered()
{
    trace("Getting File path and name to save.");
    FilePath = QFileDialog::getSaveFileName(this);

    simFile.setFileName(FilePath);

    if(simFile.open(QIODevice::ReadWrite| QIODevice::Text))
    {
        trace("File created:");
        trace(FilePath);
        simFile.close();
    }

}


void MainWindow::on_actionOpen_triggered()
{
    trace("Getting File path and name to open.");
    FilePath = QFileDialog::getOpenFileName(this);
     simFile.setFileName(FilePath);

    if(simFile.open(QIODevice::ReadWrite| QIODevice::Text))
    {
        trace("File opened:");
        trace(FilePath);



       QTextStream in(&simFile);
       while (!in.atEnd()) {
              QString line = in.readLine();
              process_line(line);
          }
       simFile.close();
    }

}

void MainWindow::on_actionSave_triggered()
{
    trace("Saving File.");
    if(!(simFile.open(QIODevice::ReadWrite| QIODevice::Text)))
    {
        //add get file path code here
        trace("No File to save.");
    }
    else{
       QTextStream out(&simFile);
       out << "Number of simulations run:\n" << simCount << "\n";
       for(int i = 0; i <simCount; i++)
       {
           out << "Simulation number:\n" << simDataArray[i]->simIndex  << "\n";
           out << "Simulation runtime:\n" << simDataArray[i]->runTime << "\n";
           out << "Number of Masters:\n" << simDataArray[i]->masters << "\n";
           out << "Maximum packet size:\n" << simDataArray[i]->maxpacket << "\n";
           out << "Minimum packet size:\n" << simDataArray[i]->minpacket << "\n";
           out << "Number of collisions:\n" << simDataArray[i]->colisions << "\n";
           out << "Number of received:\n" << simDataArray[i]->received << "\n\n";
       }
       simFile.close();
   }
}


void MainWindow::on_actionExit_triggered()
{
    //still need to add this
    trace("Ask to save, then exit.");
}

void MainWindow::process_line(QString myLine)
{
    myLine;
}

